require("dotenv").config();
const jwt = require("jsonwebtoken");
const express = require("express");
const cors = require("cors");
const app = express();
const port = 3001;
app.use(cors());
app.use(express.json());

var tokens=[];

app.post("/", (req, res) => {
  const { token } = req.body;
  console.log(tokens)
  try{
    let authState= tokens.filter( i => (i.token=== token))
    res.json({
      auth: authState[0].auth,
    });
  } catch(e) {
    res.json({
      auth: '',
    });
  }
})

app.post("/login", (req, res) => {
  const ADMIN_U = "admin1";
  const ADMIN_P = "7215ee9c7d9dc229d2921a40e899ec5f";
  const USER_U = "user2";
  const USER_P = "7215ee9c7d9dc229d2921a40e899ec5f";
  const { username, password } = req.body;
  if (username === ADMIN_U && password === ADMIN_P) {
    const user = {
      id: 1,
      username: "admin",
      rand: Math.random(),
    };
    const token = jwt.sign(user, 'secret');
    tokens.push({token: token, auth:'admin'})
    res.json({
      user,
      token,
    });
  } else if (username === USER_U && password === USER_P){
    const user = {
      id: 2,
      username: "user2",
      rand: Math.random(),
    };
    const token = jwt.sign(user, 'secret');
    tokens.push({token: token, auth:'user'})
    res.json({
      user,
      token,
    });
  } else {
    res.json({
      user: undefined,
      token: undefined,
    });
  }
})

app.post("/logout", (req, res) => {
  const { token } = req.body;
  tokens.splice(tokens.indexOf(tokens.filter( i => (i.token=== token))))
  console.log(tokens)
  res.json({
  });
})

app.post("/data/table", (req, res) => {
  const { token } = req.body;
  let auth= tokens.filter( i => (i.token=== token))[0].auth
  var tableData= []
  console.log("authState")
  if (auth==="admin"){
    var tableData= [
      {
        id: '12987122',
        name: 'Tom',
        amount1: '234',
        amount2: '3.2',
        amount3: 10,
      },
      {
        id: '12987123',
        name: 'Tom',
        amount1: '165',
        amount2: '4.43',
        amount3: 12,
      },
      {
        id: '12987124',
        name: 'Tom',
        amount1: '324',
        amount2: '1.9',
        amount3: 9,
      },
      {
        id: '12987125',
        name: 'Tom',
        amount1: '621',
        amount2: '2.2',
        amount3: 17,
      },
      {
        id: '12987126',
        name: 'Tom',
        amount1: '539',
        amount2: '4.1',
        amount3: 15,
      },
    ]

  } else if (auth==="user") {
    var tableData= [
      {
        id: '12987126',
        name: 'Tom',
        amount1: '539',
        amount2: '4.1',
        amount3: 15,
      },
    ]
  } else {
    var tableData= []
  }
  console.log(tableData)
  res.json({
    tableData,
  });
})

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`);
});
